package com.lqm.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lqm.common.constant.ProductConstant;
import com.lqm.common.to.SkuHasStockVo;
import com.lqm.common.to.SkuReductionTo;
import com.lqm.common.to.SpuBoundTo;
import com.lqm.common.to.es.SkuEsModel;
import com.lqm.common.utils.PageUtils;
import com.lqm.common.utils.Query;
import com.lqm.common.utils.R;
import com.lqm.mall.product.dao.SpuInfoDao;
import com.lqm.mall.product.entity.*;
import com.lqm.mall.product.feign.CouponFeignService;
import com.lqm.mall.product.feign.SearchFeignService;
import com.lqm.mall.product.feign.WareFeignService;
import com.lqm.mall.product.service.*;
import com.lqm.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SearchFeignService searchFeignService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService imagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu,spu_info
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2 保存描述图片
        List<String> descrip=vo.getDecript();
        SpuInfoDescEntity descEntity=new SpuInfoDescEntity();
        //此处获取spuId方法存疑 自增长可以通Option注解获取，不自增长通过selectKey获取
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",",descrip));
        this.saveSpuInfoDesc(descEntity);
        //3 保存spu图片集
        List<String> images=vo.getImages();
        imagesService.saveImages(images,spuInfoEntity.getId());
        //4 保存规格参数
        List<BaseAttrs> baseAttrs=vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities=baseAttrs.stream().map((baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity=new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            AttrEntity id=attrService.getById(baseAttr.getAttrId());
            //TODO 检查
            productAttrValueEntity.setAttrName(id.getAttrName());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            return productAttrValueEntity;
        })).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntities);
        //5 远程服务保存 spu的积分信息 mall_sms->sms_spu_bounds
        Bounds bounds=vo.getBounds();
        SpuBoundTo spuBoundTo=new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        //TODO 此处远程服务调用时事务失效
        R r=couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }
        //5 1) sku的基本信息：pms_sku_info
        List<Skus> skus=vo.getSkus();
        if(skus!=null && skus.size()>0){
            skus.forEach((item)->{
//                private String skuName;
//                private BigDecimal price;
//                private String skuTitle;
//                private String skuSubtitle;
                SkuInfoEntity skuInfoEntity=new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                item.getImages().forEach((img)->{
                    if(img.getDefaultImg()!=0){
                        skuInfoEntity.setSkuDefaultImg(img.getImgUrl());
                    }
                });
                skuInfoService.save(skuInfoEntity);
                List<SkuImagesEntity> skuImagesEntities=item.getImages().stream().map((img)->{
                    SkuImagesEntity skuImagesEntity=new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    return skuImagesEntity;
                }).filter((entity)->{
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //保存sku图片
                skuImagesService.saveBatch(skuImagesEntities);
                //保存sku销售属性
                List<Attr> attrs=item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities=attrs.stream().map((attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity=new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                })).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5 4)远程服务调用 sku的优惠,满减等信息 mall_sms->sms_sku_full_reductio,mall_sms->sms_sku_ladder
                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if(skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))>0){
                    R r1=couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode()!=0){
                        log.error("远程保存sku信息失败");
                    }
                }

            });
        }

    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity descEntity) {
        spuInfoDescService.save(descEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
//        status=0&key=11&brandId=2&catelogId=225
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String catelogId= (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !catelogId.equals("0")){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId= (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !brandId.equals("0")){
            wrapper.eq("brand_id",brandId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities=skuInfoService.getBySkusBySpuId(spuId);

        //TODO 查询attr
        List<ProductAttrValueEntity> attrValueEntities=productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));
        List<Long> attrIds=attrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchAttrIds=attrService.selectSearchAttrIds(attrIds);
        HashSet<Long> idSet=new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attr> attrs=attrValueEntities.stream().filter((item)->idSet.contains(item.getAttrId())).map((item)->{
            SkuEsModel.Attr attr=new SkuEsModel.Attr();
            BeanUtils.copyProperties(item,attr);
            return attr;
        }).collect(Collectors.toList());

        List<Long> skuIds=null;

        List<SkuHasStockVo> skuHasStockVos=null;
        Map<Long,Boolean> stockMap=null;
        try{
            //TODO 远程查询库存 hasStock
            skuIds=skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R r=wareFeignService.getSkuHasStock(skuIds);
            //TODO
            com.alibaba.fastjson.TypeReference<List<SkuHasStockVo>> typeReference=new TypeReference<List<SkuHasStockVo>>(){};
            skuHasStockVos=r.getData(typeReference);
            stockMap=skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,SkuHasStockVo::getHasStock));
        }catch (Exception e){
            log.error("远程调用异常：{}",e);
        }


        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels=skuInfoEntities.stream().map((item)->{
            SkuEsModel skuEsModel=new SkuEsModel();
            BeanUtils.copyProperties(item,skuEsModel);
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());
            skuEsModel.setHotScore(0L);//默认0
            CategoryEntity categoryEntity=categoryService.getById(item.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            BrandEntity brandEntity=brandService.getById(item.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setAttrs(attrs);
            if(finalStockMap !=null){
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }else{
                skuEsModel.setHasStock(true);
            }
            return skuEsModel;
        }).collect(Collectors.toList());
        //TODO 远程调用保存ES数据
        R r=searchFeignService.productStatusUp(skuEsModels);
        if(r.getCode()==0){
            //TODO 调用成功
            //变更状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //TODO 调用失败,重复，接口幂等性
        }

    }



}